package strategies

import (
	"fmt"
	"time"

	"monitor.ilin.cc/internal/pkg/indicators"
	"monitor.ilin.cc/internal/pkg/strategy"
)

// RSI策略配置
type RSIConfig struct {
	Period      int           // RSI周期
	OverSold    float64       // 超卖阈值
	OverBought  float64       // 超买阈值
	MinInterval time.Duration // 最小交易间隔
}

// 默认配置
var DefaultRSIConfig = RSIConfig{
	Period:      14,
	OverSold:    30,
	OverBought:  70,
	MinInterval: 1 * time.Hour,
}

// RSI策略
type RSIStrategy struct {
	symbol    string
	config    RSIConfig
	rsi       *indicators.RSI
	lastTrade time.Time
	position  bool
}

func NewRSIStrategy(symbol string, config *RSIConfig) *RSIStrategy {
	cfg := DefaultRSIConfig
	if config != nil {
		cfg = *config
	}

	return &RSIStrategy{
		symbol: symbol,
		config: cfg,
		rsi:    indicators.NewRSI(cfg.Period),
	}
}

func (s *RSIStrategy) GetSymbol() string {
	return s.symbol
}

func (s *RSIStrategy) Update(price float64, timestamp time.Time) (*strategy.Signal, error) {
	// 更新RSI
	if err := s.rsi.Update(price); err != nil {
		return nil, fmt.Errorf("更新RSI失败: %v", err)
	}

	rsiValue := s.rsi.GetValue()

	// 检查交易间隔
	if time.Since(s.lastTrade) < s.config.MinInterval {
		return nil, nil
	}

	// 生成信号
	if rsiValue <= s.config.OverSold && !s.position {
		// 超卖买入信号
		s.position = true
		s.lastTrade = timestamp
		return &strategy.Signal{
			Type:      strategy.BuySignal,
			Price:     price,
			Timestamp: timestamp,
			Reason:    fmt.Sprintf("RSI超卖：当前值%.2f", rsiValue),
		}, nil
	} else if rsiValue >= s.config.OverBought && s.position {
		// 超买卖出信号
		s.position = false
		s.lastTrade = timestamp
		return &strategy.Signal{
			Type:      strategy.SellSignal,
			Price:     price,
			Timestamp: timestamp,
			Reason:    fmt.Sprintf("RSI超买：当前值%.2f", rsiValue),
		}, nil
	}

	return nil, nil
}

func (s *RSIStrategy) Reset() {
	s.rsi.Reset()
	s.position = false
}
